#!/usr/bin/bash
serverDomain=devops-test.36ve.com #部署服务器域名
serverPort=80 #部署服务器端口
company="lhwl"  #公司名
systemVersion="centos7"  #本系统版本
clientId="1617584765828" #该服务器在部署系统中的id

interval=1
dateDay=$(date +%Y%m%d)
dateSecond=$(date +%Y%m%d%H%M%S)
nmapPath="/usr/bin/nmap"
logdir="/${company}/bin/tmp/";mkdir -p ${logdir}
logDay=${logdir}/while.${dateDay}.log



function checkFileExist() {
    if [ -f ${1} ]; then
      echo true
    else
      echo false
    fi
}
##checkFileExist
function yumInstall() {
    shell=$(yum install ${1} -y)
    shell
}
##yumInstall
yum install vim-common -y
function killSelf(){
  ps -ef |grep `echo $0`|grep -v grep|awk -F ' ' '{print $2}'|xargs kill -9
}
##killSelf
function pass(){
  echo '' >> /dev/null
}
##pass
function logDay() {
  export PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
  echo  $* >> ${logDay}
}
##logDay
function checkNmap() {
  checkNmapResult=$(checkFileExist ${nmapPath})
  if [[ ${checkNmapResult}x == "false"x ]]; then
      logDay 没找到 : "${nmapPath}" ,进行安装
      yum Install nmap
      checkNmapYumResult=$(checkFileExist ${nmapPath})
      if [[ ${checkNmapYumResult}x == "false"x ]]; then
        logDay "安装失败 nmap "
        killSelf
      fi
      ##安装失败 nmap
  fi
  ##解决nmap不存在的问题
}
##解决nmap不存在的问题
checkPortOpenCount=1
function checkPortOpen() {
  checkNmap  ##解决nmap不存在的问题
  # shellcheck disable=SC2006
  checkPortOpenResult=`${nmapPath} ${serverDomain} -p ${serverPort}`
  checkPortOpenGrepResult=$(echo "${checkPortOpenResult}"|grep open)
  if [ "${checkPortOpenGrepResult}"x == ""x ]; then
      logDay "无法连接部署服务器"
      sleep $(echo "${checkPortOpenCount} *5"|bc)
      checkPortOpenCount=$(echo "${checkPortOpenCount} +1"|bc)
      if [[ $(echo "${checkPortOpenCount} >3"|bc) = 1 ]]; then
          killSelf
      fi
      checkPortOpen
  fi
}
##checkPortOpen  #检测端口是否开放
function curlGet() {
    shell="curl $1"
    #logDay $shell
    echo $($shell)
    return
}
##curlGet
##getTaskIdsUrl
function getTaskCommandUrl() {
    #logDay "获取 获得任务内容的url"
    url="http://${serverDomain}:${serverPort}/javacmdb/clientServlet?action=getSubtaskCommand&serverId=${clientId}&subtaskId=${1}"
    #logDay ${url}
    echo ${url}
    return
}
##getTaskCommandUrl
function getTaskIds() {
  shell="curl http://${serverDomain}:${serverPort}/javacmdb/clientServlet?action=getSubtaskIds&serverId=${clientId}"
  logDay "获取任务ids" ${shell}
  getTaskIdsResult=$(${shell})
  logDay "ids 结果为:" ${getTaskIdsResult}
  #getTaskIdsResult=$(curl http://${serverDomain}:${serverPort}/javacmdb/clientServlet?action=getTaskIds&serverId=${clientId})
  echo "${getTaskIdsResult}"
  return
}
##getTaskIds
function reportTaskStatus() {
  reportTaskStatusPostUrl="http://${serverDomain}:${serverPort}/javacmdb/clientServlet"
  unicodeResult=$(echo ${3} | tr -d '\n' | xxd -plain | sed 's/\(..\)/%\1/g') #把中文,空格等转换成unicode编码,服务器会自动解码的
  logDay 参数3是: ${3}
  #unicodeResult=$(echo ${3}  | xxd -plain | sed 's/\(..\)/%\1/g') #把中文,空格等转换成unicode编码,服务器会自动解码的
  logDay 转码后的参数3是: ${unicodeResult}
  shell="curl -G -d "action=reportSubtaskStatus" -d "serverId=${clientId}" -d "subtaskId=${1}"  -d "status=${2}"  -d "result=${unicodeResult}" "${reportTaskStatusPostUrl}""
  logDay "报告结果的命令是:" ${shell}
  reportResult=$(curl  -d "action=reportSubtaskStatus" -d "serverId=${clientId}" -d "subtaskId=${1}"  -d "status=${2}"  -d "result=${unicodeResult}" "${reportTaskStatusPostUrl}")
  #结果必须用变量reportResult接收,否则结果会被执行,所以会报错
  #echo ${reportResult}
  #return #返回必须接收,不接收,就会输出到屏幕
}
##reportTaskStatus
function whileBody() {
    logDay "开始执行" $(date +%Y%m%d%H%M%S)
    taskIds=$(echo $(getTaskIds)|sed "s/,/ /g")  #获取ids

    if [ "${taskIds}"x == ""x ]; then
        sleep 10
        return
    fi

    for taskId in `echo ${taskIds}` ;do
      taskIdsArray[${#taskIdsArray[@]}]=${taskId}
    done
    taskIdsArraySize=${#taskIdsArray[@]}  #获取id 数量
    if [ ${taskIdsArraySize} -eq 0 ]; then
        return
    fi

    for (( i = 0; i < ${taskIdsArraySize}; i++ )); do
        taskId=${taskIdsArray[${i}]}
        logDay ${i}/${taskIdsArraySize} taskId : ${taskId}
        logDay "去请求task command的命令:" "curl $(getTaskCommandUrl ${taskId})"
        command=$(curlGet $(getTaskCommandUrl ${taskId})) #请求任务内容

        logDay "即将执行的命令是:" ${command}
        commandResult=$(${command})  ##执行 #注意:一次只能给一条命令
        #commandResult=$(echo ${command}|awk '{run=$0;system(run)}') #这样采集不到执行结果
        #commandResult=$(echo ${command}|awk '{system($0)}') #这样采集不到执行结果

        if [ $? == 0 ]; then
          status="true"
          logDay 执行结果 ${commandResult}
          reportTaskStatus ${taskId} ${status} "${commandResult}" #返回执行状态
          logDay ${command} "本任务结束" 状态 ${status}
        else
          status="false"
          logDay 执行结果 ${commandResult}
          reportTaskStatus ${taskId} ${status} "${commandResult}" #返回执行状态
          logDay ${command} "本任务结束" 状态 ${status} 停止所有任务
          break
        fi
    done
    sleep ${interval}  #循环间隔
    logDay "结束执行" $(date +%Y%m%d%H%M%S)
    logDay
}

while [ 1 -le 2 ]; do
    whileBody
    sleep 10
done







